package com.jianglin.controller;
import com.github.pagehelper.PageInfo;
import com.jianglin.model.Complaint;

import com.jianglin.service.IComplaintService;
import com.jianglin.service.IOwnerService;
import com.jianglin.util.JsonObject;
import com.jianglin.util.JwtUtil;
import com.jianglin.util.R;
import com.jianglin.model.Owner;
import io.swagger.annotations.Api;

import io.swagger.annotations.ApiOperation;

import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;

/**
 *
 *
 * @author liyijia
 */
@Api(tags = {"投诉管理"})
@CrossOrigin(origins="http://localhost:5500")
@RestController
@RequestMapping("/complaint")
public class ComplaintController {

    @Resource
    private IComplaintService complaintService;
    @Resource
    private IOwnerService ownerService;

    @Resource
    private JwtUtil jwtUtil;

    @GetMapping("/queryComplaintAll")
    public JsonObject<Complaint> queryComplaintAll(Complaint complaint,
                                        @RequestParam(defaultValue = "1") Integer page,
                                        @RequestParam(defaultValue = "15") Integer limit) {
        PageInfo<Complaint> pageInfo = complaintService.findComplaintAll(page, limit, complaint);
        return new JsonObject<>(0, "ok", pageInfo.getTotal(), pageInfo.getList());
    }
    @GetMapping("/queryComplaintAll2")
    public JsonObject<Complaint> queryComplaintAll2(
            @RequestParam(required = false) String comId,      // 接收字符串
            @RequestParam(required = false) Integer status,    // 接收整数
            HttpServletRequest request,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "15") Integer limit) {

        //先获取业主的token
        String authHeader = request.getHeader("Authorization");
        String token = authHeader.substring(7).trim();
        //根据token获取username
        String username = jwtUtil.getUsernameFromToken(token);


        //根据username获取登录账号得业主id
        Owner owner=ownerService.queryOwnerByName(username);
        Complaint complaint = new Complaint();

        // 将空字符串转换为 null
        if (comId != null && comId.isEmpty()) {
            comId = null;
        }

        // 尝试将 comId 转换为整数
        Integer comIdInt = null;
        if (comId != null) {
            try {
                comIdInt = Integer.parseInt(comId);
            } catch (NumberFormatException e) {
                // 转换失败，保持 null
            }
        }

        complaint.setComId(comIdInt);
        complaint.setStatus(status);
        complaint.setOwnerId(owner.getId());

        PageInfo<Complaint> pageInfo = complaintService.findComplaintAll(page, limit, complaint);
        return new JsonObject<>(0, "ok", pageInfo.getTotal(), pageInfo.getList());
    }



@ApiOperation(value = "新增投诉")
@RequestMapping("/add")
public R add(@RequestBody Complaint complaint, HttpServletRequest request) {
    // 1. 验证投诉ID是否合法
    if (complaint.getComId() == null) {
        return R.fail("投诉类型不能为空");
    }

    // 2. 从Token中获取用户名
    String authHeader = request.getHeader("Authorization");
    if (authHeader == null || !authHeader.startsWith("Bearer ")) {
        return R.fail("认证信息不合法");
    }

    String token = authHeader.substring(7).trim();
    String username = jwtUtil.getUsernameFromToken(token);

    // 3. 根据用户名获取业主信息
    Owner owner = ownerService.queryOwnerByName(username);
    if (owner == null) {
        return R.fail("业主信息不存在");
    }

    // 4. 设置投诉信息
    complaint.setOwnerId(owner.getId());
    complaint.setStatus(0);
    complaint.setComDate(new Date());

    // 5. 保存投诉记录
    int num = complaintService.add(complaint);
    if (num > 0) {
        return R.ok();
    }
    return R.fail("投诉提交失败");

}

    @ApiOperation(value = "删除")
    @RequestMapping("/deleteByIds")
    public R deleteByIds(@RequestParam String ids) {
        Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .forEach(complaintService::delete);
        return R.ok();
    }

    @ApiOperation(value = "更新")
    @RequestMapping ("/update")
    public R update(@RequestParam Integer id) {
        Complaint complaint = complaintService.findById(Long.valueOf(id));
        if (complaint == null) {
            return R.fail("投诉记录不存在");
        }

        complaint.setStatus(1);
        return complaintService.updateData(complaint) > 0 ? R.ok() : R.fail("处理失败");
    }

    @ApiOperation(value = "查询分页数据")
    @GetMapping("/page")
    public PageInfo<Complaint> findListByPage(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageCount) {
        return complaintService.findListByPage(page, pageCount);
    }

    @ApiOperation(value = "id查询")
    @GetMapping("/{id}")
    public Complaint findById(@PathVariable Long id) {
        return complaintService.findById(id);
    }
}
